import md5 from 'md5';
import $ from "jquery";
export const randomWord = (randomFlag, min, max) => {
    var str = "",
        range = min,
        pos = "",
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}
// const md5 = require('md5')
// const qs = require('querystring')
export const ToUrlParams = (obj) => {
    let string = ''
    for (let k in obj) {
        if (k !== "sign" && obj[k] !== '' && !Array.isArray(obj[k])) {
            string += `${k}=${obj[k]}&`
        }
    }
    let result = string.replace(/(^&*)|(&*$)/g, "")
    return result
}

/**
 * 计算签名
 * @param {*} data 
 * @param {*} param1 
 */
export const getSign = (data, {
    appid,
    appsecret,
    noncestr,
    timestamp,
    method = 'POST',
    key = "yxp"
}) => {
    let obj = {
        appid,
        appsecret,
        noncestr,
        method,
        timestamp,
        ...data
    }
    const ordered = {};
    Object.keys(obj).sort().forEach(function (key) {
        ordered[key] = obj[key];
    });
    let querystring = ToUrlParams(ordered)
    let result = `${querystring}${key}`
    console.log(result)
    let sign = md5(result)
    sign = sign.toUpperCase()
    return sign
}

function strSimilarity2Number(s, t) {
    var n = s.length,
        m = t.length,
        d = [];
    var i, j, s_i, t_j, cost;
    if (n == 0) return m;
    if (m == 0) return n;
    for (i = 0; i <= n; i++) {
        d[i] = [];
        d[i][0] = i;
    }
    for (j = 0; j <= m; j++) {
        d[0][j] = j;
    }
    for (i = 1; i <= n; i++) {
        s_i = s.charAt(i - 1);
        for (j = 1; j <= m; j++) {
            t_j = t.charAt(j - 1);
            if (s_i == t_j) {
                cost = 0;
            } else {
                cost = 1;
            }
            d[i][j] = Minimum(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
        }
    }
    return d[n][m];
}

function Minimum(a, b, c) {
    return a < b ? (a < c ? a : c) : (b < c ? b : c);
}
//两个字符串的相似程度，并返回相似度百分比
export const diffStrScore = (s, t) => {
    var l = s.length > t.length ? s.length : t.length;
    var d = strSimilarity2Number(s, t);
    console.log(d, l)
    return Math.ceil((1 - d / l) * 100);
}
/**
 * 语法处用于查找是否有下一句有则返回 current
 * @param {*} list 查询列表
 * @param {*} currentIndex 当前元素
 * @param {*} targetKey 查询条件key
 * @param {*} targetVal 查询条件val
 */
export const findNextTarget = (list, currentId, targetKey, targetVal) => {
    let currentIndex = list.findIndex(v => v.id === currentId)
    let arrPre = [], arrNext = [], preCurrent = null, nextCurrent = null
    if (currentIndex === 0) {
        arrNext = list.slice(1, list.length)
    } else if (currentIndex === list.length - 1) {
        arrPre = list.slice(0, currentIndex)
    } else if (currentIndex > 0) {
        arrPre = list.slice(0, currentIndex)
        arrNext = list.slice(currentIndex + 1, list.length)
    }
    if (!arrPre.length && !arrNext.length) {
        return -1
    } else if (!arrPre.length) {
        nextCurrent = arrNext.find(v => v[targetKey] === targetVal)
    } else if (!arrNext.length) {
        preCurrent = arrPre.find(v => v[targetKey] === targetVal)
    } else {
        nextCurrent = arrNext.find(v => v[targetKey] === targetVal)
        preCurrent = arrPre.find(v => v[targetKey] === targetVal)
    }
    return nextCurrent ? nextCurrent : preCurrent
}

export const blobToDataURI = (blob, callback) => {
    var reader = new FileReader()
    reader.readAsDataURL(blob)
    reader.onload = function (e) {
        callback(e.target.result)
    }
}

export const dataURItoBlob = (base64Data) => {
    //console.log(base64Data);//data:image/png;base64,
    var byteString;
    if(base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1]);//base64 解码
    else{
        byteString = unescape(base64Data.split(',')[1]);
    }
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];//mime类型 -- image/png

    // var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    // var ia = new Uint8Array(arrayBuffer);//创建视图
    var ia = new Uint8Array(byteString.length);//创建视图
    for(var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var blob = new Blob([ia], {
        type: mimeString
    });
    return blob;
}

export const getQueryString = (name) => {
    let reg = `(^|&)${name}=([^&]*)(&|$)`
    let r = window.location.search.substr(1).match(reg); 
    if (r != null) return unescape(r[2]);
    return null; 
}

export const makeLockTask = (e, cmd = 'lock', opts = {}) => {
    let o = $(e.target).parents(opts.elem || '.synclock')
    let id = e.__id__ || $(o).attr('__id__') || `yxp:a:${new Date().getTime()}`
    console.log(33, id,  $(o).attr('__id__'))
    if(cmd == 'lock'){
      let position = o.offset()
      let box = {w: o.width(), h: o.height()}
      let wh = {
        w: opts.w || box.w,
        h: opts.h || box.h
      }
      wh.t = position.top
      wh.l = position.left
      $('body').append(`<div id="${id}" style="background-color:rgba(155,235,255,.5);z-index:1000;overflow:hidden;position:absolute;width:${wh.w}px;height:${wh.h}px;top:${wh.t}px;left:${wh.l}px"></div>`)
      $(o).attr('__id__', id)
      console.log(55, $(o).attr('__id__'))
      // 防止死锁
      window[`lock:${id}`] = setTimeout(() => {
        document.getElementById(id) && document.getElementById(id).remove()
      }, opts.lockTime || 10*1000)
    }else{
      if(opts.that){
        opts.that.$nextTick(() => {
          document.getElementById(id) && document.getElementById(id).remove()
        })
      }else{
        document.getElementById(id) && document.getElementById(id).remove()
      }
      clearTimeout(window[`lock:${id}`])
    }
}

export const isClient = () => {
    return !!window.require && !!window.require('electron')
}
export const openBrowser = (url) => {
    if (isClient()) {
      window.require('electron').shell.openExternal(url)
    } else {
      window.open(url)
    }
  }